﻿using System.Collections.Generic;
using NHibernate.Criterion;


using Light.Framework.Castle;
using Light.Framework.Component;
using Light.Framework.Contract;
using Light.Framework.Model;
using Light.Weixin.Contract;
using Light.Weixin.Model;

namespace Light.Weixin.Component
{
    public class WxAppComponent : BaseComponent<WxApp>, IWxAppComponent, IDataImport
    {

        public WxApp Get(WxAppType type)
        {
            ICriterion criterion1 = GetNotDeletedCriterion();
            criterion1 = Expression.And(criterion1, Expression.Eq("Type", type));

            ICriterion criterion2 = Expression.And(criterion1, Expression.Eq("IsDefault", true));

            WxApp obj = EntityMediator<WxApp>.FindFirst(criterion2);
            if (obj == null)
                obj = EntityMediator<WxApp>.FindFirst(criterion1);

            ServerApplication.Evit(obj);

            return obj;
        }

        public WxApp GetByAppId(string appId)
        {
            return Get("AppID", appId);
        }

        public WxApp GetByOrginalID(string orginalId)
        {
            return Get("OriginalID", orginalId);
        }

        public override WxApp Get(string propertyName, object value)
        {
            using (new GuestUser())
            {
                ICriterion criterion = Expression.Eq(propertyName, value);
                criterion = Expression.And(criterion, GetNotDeletedCriterion());

                WxApp obj = EntityMediator<WxApp>.FindFirst(criterion);
                ServerApplication.Evit(obj);

                return obj;
            }
        }

        protected override void BeforeSave(WxApp obj)
        {
            base.BeforeSave(obj);
            SetDefault(obj);
        }

        protected override ICriterion GetDefaultCriterion<TD>(TD obj)
        {
            return Expression.Eq("Type", (obj as WxApp).Type);
        }

        protected override ICriterion CreateCriterion(WxApp model)
        {
            return Expression.Eq("AppID", model.AppID);
        }

        protected override System.Func<WxApp, bool> CreateFunc(WxApp model)
        {
            return w => w.AppID == model.AppID;
        }
    }
}
